App.controller('publishController', ['$rootScope', '$scope', '$state', 'Page', function ($rootScope, $scope, $state, Page) {

    //客户下拉框
    Page.ajaxPostQuiet('customer/queryCustomer.do', null, function (resp) {
        $scope.customerList = resp.data;
    });


    $scope.publishBillGrid = {

        column_defs: [
            {
                target : 1,
                template: function(row) {
                     return '<a href="javascript:void(0)" ed-click="view">' + row.billNo + '</a>';
                }
            },
            {
                target: 10,
                buttons: [
                    {
                        name: '编辑',
                        clazz: 'btn-edit',
                        icon: 'fa-edit',
                        event: function(row){
                    		$scope.billAddModal.open(row);
                        },
                        visiable: function(row) {
                            if(row.publishBillStatus == "0") { //只有未提交的时候显示
                                return true
                            }
                            return false;
                        }
                    },
                    {
                        name: '删除',
                        clazz: 'btn btn-delete',
                        icon: 'fa-trash-o',
                        event: function(row){
                    		 Page.confirm("确定要删除吗？", function () {
				                Page.ajaxPost('publishBill/delete.do', row, function () {
				                    $scope.publishBillGrid.query();
				                });
				            });
                        },
                        visiable: function(row) {
                            if(row.publishBillStatus == "0") { //只有未提交的时候显示
                                return true
                            }
                            return false;
                        }
                    },
                    {
                        name: '提交审核',
                        clazz: 'btn btn-success',
                        icon: 'glyphicon glyphicon-play-circle',
                        event: function(row){
                    		Page.confirm("确定要提交审核吗？", function () {
				                Page.ajaxPostQuiet('publishBill/startPublishBill.do', {billId : row.billId}, function () {
				                    Page.notice("提交审核成功!");
				                    $scope.publishBillGrid.query();
				                });
				            });
                        },
                        visiable: function(row) {
                            if(row.publishBillStatus == "0" || row.publishBillStatus == "2") { //只有未提交的时候显示
                                return true
                            }
                            return false;
                        }
                    },
                    {
                        name: '上刊详情',
                        clazz: 'btn btn-success',
                        icon: 'glyphicon glyphicon-list-alt',
                        event: function(row){
                    		$scope.makeBillViewModal.open(row.billId);
                        },
                        visiable: function(row) {
                            return row.publishBillStatus == "3" || row.publishBillStatus == "4";
                        }
                    }
                ]
            }
        ],
        view : function(row) {
        	$scope.billViewModal.open(row);
        },
        showAll : function(row) {
            $scope.showBillNo = row.billNo;
            $scope.billNoTips.show(event);
        },
        showAllLeave : function(row) {
            $scope.billNoTips.hide();
        }
    }

    $scope.billViewModal = {
    	open : function(bill){
    		this.bill = bill;
    		this.show();
    	},
        onShow : function() {
            this.setTitle("单号-" + this.bill.billNo);
            Page.ajaxPostQuiet('publishBill/queryBillDetails.do', {billId : this.bill.billId}, function (resp) {
                $scope.billViewModal.bill.billDetails = resp.data.array;
				var bidFiles = resp.data.fileArray;
				var bidImgs = resp.data.imgArray;
				$scope.billViewModal.publishFile = bidFiles.length > 0 ? bidFiles[0]:null;
				$scope.billViewModal.adModelImgs = bidImgs;
            });
        }
    }

    $scope.billAddModal = {
    	open : function(bill){
    		this.publishBill = bill || {};
    		this.busResources = new Map();
            this.stopResources = new Map();
            this.publishFile = null;
            this.adModelImgs = [];
            this.resourcesSize = 0;
            this.show();
    	},
        onShow : function() {
    		this.billTypeWatch = $scope.$watch('billAddModal.publishBill.billType', function (newValue, oldValue, $scope) {
				if (newValue == undefined || newValue == '') {
				     $scope.billAddModal.mediaTypes = [];
				     return;
				}
				Page.ajaxPostQuiet('mediaType/getMediaTypesByParentId.do', {parentId : $scope.billAddModal.publishBill.billType}, function (resp) {
	            	$scope.billAddModal.mediaTypes = resp.data;
	        	});
			});
    		
    		this.resourcesSizeWatch = $scope.$watch('billAddModal.resourcesSize', function (newValue, oldValue, $scope) {
				if (newValue == 0) {
				 	$('#billAddModalCustomerId').attr("disabled",false);
				 	$('#billAddModalbillType').attr("disabled",false);
				 	$('#billAddModalmediaType').attr("disabled",false);
				}else if(newValue > 0){
					$('#billAddModalCustomerId').attr("disabled",true);
					$('#billAddModalbillType').attr("disabled",true);
					$('#billAddModalmediaType').attr("disabled",true);
				}
			});
    		
    		if(this.publishBill.billId != undefined && this.publishBill.billId != ''){
            	Page.ajaxPostQuiet('publishBill/queryBillDetails.do', {billId : this.publishBill.billId}, function (resp) {
				                var data = resp.data.array;
				                for (var i = 0; i < data.length; i++) {
				                    if($scope.billAddModal.publishBill.billType == "1") {
					                    $scope.billAddModal.busResources.put(data[i].resourceId,data[i]);
					                } else if($scope.billAddModal.publishBill.billType == "2") {
					                    $scope.billAddModal.stopResources.put(data[i].resourceId,data[i]);
					                }
				                    if(i == 0){
				                		$scope.billAddModal.publishBill.mediaType = data[i].mediaType;
				                	}
				                }
				                $scope.billAddModal.resourcesSize = $scope.billAddModal.stopResources.size() + $scope.billAddModal.busResources.size();
				                
				                var bidFiles = resp.data.fileArray;
				                var bidImgs = resp.data.imgArray;
				                $scope.billAddModal.publishFile = bidFiles.length > 0 ? bidFiles[0]:null;
				                $scope.billAddModal.adModelImgs = bidImgs;
				                
				                
				 });
            }else{
            	var date = new Date();
            	this.publishBill.billNo = date.getTime();
            }
    		
            this.setTitle("单号-" + this.publishBill.billNo);
        },
        clickAdd : function() {
            if(this.publishBill.customerId == undefined || this.publishBill.customerId == "") {
                Page.notice("请选择经营单位!");
                return;
            }
            if(this.publishBill.billType == undefined || this.publishBill.billType == "" 
            	|| this.publishBill.mediaType == undefined || this.publishBill.mediaType == "") {
                Page.notice("请选择上刊类型及媒体方式!");
                return;
            }
            $scope.scheduleModal.open({
            	customerId : this.publishBill.customerId, 
            	mediaId: this.publishBill.mediaType,
            	billType : this.publishBill.billType},
            	function(resources){
            		if(resources != undefined && resources.elements.length > 0) {
		                for (var i = 0; i < resources.elements.length; i++) {
		                	var resource = resources.elements[i].value;
		                	if($scope.billAddModal.publishBill.billType == "1") {
		                    	$scope.billAddModal.busResources.put(resource.resourceId,resource);
			                } else if($scope.billAddModal.publishBill.billType == "2") {
			                	$scope.billAddModal.stopResources.put(resource.resourceId,resource);
			                }
		                }
		                $scope.billAddModal.resourcesSize = $scope.billAddModal.stopResources.size() + $scope.billAddModal.busResources.size();
		            }
            	});
        },
        removeResources : function(value) {
	        if(this.publishBill.billType == "1") {
	            this.busResources.remove(value.resourceId);
	        } else if(this.publishBill.billType == "2") {
	            this.stopResources.remove(value.resourceId);
	        }
	        $scope.billAddModal.resourcesSize = $scope.billAddModal.stopResources.size() + $scope.billAddModal.busResources.size();
    	},
        removePublishFile : function(){
        	this.publishFile = null;
        },
        removeAdModelImg : function(img){
        	for(var i = 0 ;i < this.adModelImgs.length; i++){
        		if(this.adModelImgs[i].path == img.path){
        			this.adModelImgs.splice(i,1);
        			return;
        		}
        	}
    	},
        onOkClick : function() {
        	var param = {};
	    	param.busResources = this.busResources.elements;
	    	param.stopResources = this.stopResources.elements;
	    	param.customerId = this.publishBill.customerId;
	    	param.billNo = this.publishBill.billNo;
	    	param.billType = this.publishBill.billType;
	    	param.updateBillId = this.publishBill.billId;
	    	param.billId = this.publishBill.billId;
	    	param.billContent = this.publishBill.content;
	    	param.billPublishTime = this.publishBill.publishTime;
	    	param.billPublishOffTime = this.publishBill.publishOffTime;
			param.mediaId = this.publishBill.mediaType;
	    	 if(this.publishFile != undefined) {
	    		 param.bidFiles = [this.publishFile];// 上刊资料
	         }else {
	        	 param.bidFiles = [];
	         }
	    	 if(this.adModelImgs != undefined) {
	    		 param.bidImgs = this.adModelImgs;
	         }else {
	        	 param.bidImgs = [];
	         }
	    	 
	    	if(this.publishBill.customerId == undefined || this.publishBill.customerId == "") {
                Page.notice("请选择经营单位!");
                return;
            }
            if(this.publishBill.billType == undefined || this.publishBill.billType == "" 
            	|| this.publishBill.mediaType == undefined || this.publishBill.mediaType == "") {
                Page.notice("请选择上刊类型及媒体方式!");
                return;
            }
            
	    	 if(param.busResources.length==0 && param.stopResources.length==0){
	    		 Page.notice("请编辑上刊明细!");
	    		 return false;
	    	 } 
	    	 Page.ajaxPost('publishBill/saveBillDetails.do',param, function (resp) {
	    		var data = resp.data;
	            if(data.flag){
	            	Page.notice("保存成功!");
	            	$scope.billAddModal.hide();
	    	     	$scope.billAddModal.billTypeWatch();
		    	    $scope.billAddModal.resourcesSizeWatch();
		    	    $scope.publishBillGrid.query();
	            }else {
	            	Page.notice(data.msg);
	            }
	    	 });
        },
        onHidden : function() {
        	this.billTypeWatch();
        	this.resourcesSizeWatch();
        }
    }

    $scope.scheduleModal = {
    	param : {
    		pageIndex : 0,
    		pageSize : 10,
    		month : null,// 当前月份
	        lastOrNext :null,// -1：上一月 上一年 1：下一月 下一年
	        monthOrYear :null,// 1:年 2：月
	        
	        resourceCode :null,
	        status :null,
	        startDate :null,
	        endDate :null,
	        modalResourceId :null,
	        modalBillId :null,
	        customerId :null,
	        billType :null,
	        mediaId :null,
    	},
    	data : {
    		months : [],
    		days : [],
    		dataArray : [],
    		month : null,
    		lastYear : null,
    		nextYear : null,
    		totalPages : null
    	},
    	open : function(opts,callBack){
    		this.param = angular.extend(this.param, opts);
    		if(callBack){
    			this.callBack = callBack;
    		}
    		this.show();
    	},
    	onShow : function(){
    		this.checkResources = new Map();
    		this.query();
    	},
    	preYear : function(){
	        this.param.lastOrNext = -1;
	        this.param.monthOrYear = 1;
    		this.query();
    	},
    	nextYear : function(){
    		this.param.lastOrNext = 1;
	        this.param.monthOrYear = 1;
    		this.query();
    	},
    	monthChange : function() {
    		this.param.month = this.data.month;
    		this.param.lastOrNext = null;
	        this.param.monthOrYear = null;
        	this.query();
   		},
    	preMonth : function(){
    		this.param.lastOrNext = -1;
	        this.param.monthOrYear = 2;
    		this.query();
    	},
    	nextMonth : function(){
    		this.param.lastOrNext = 1;
	        this.param.monthOrYear = 2;
    		this.query();
    	},
    	query : function(){
	        this.param.month = this.data.month;// 当前月份
	        Page.ajaxPost('schedule/queryBillSources.do', this.param, function(resp) {
	            $scope.scheduleModal.data.months = resp.data.months;
	            $scope.scheduleModal.data.days = resp.data.daysArray;
	            $scope.scheduleModal.data.dataArray = resp.data.dataArray;
	            
	            $scope.scheduleModal.data.month = resp.data.currentMonth;
	            $scope.scheduleModal.data.lastYear = resp.data.lastYear;
	            $scope.scheduleModal.data.nextYear = resp.data.nextYear;
	            $scope.scheduleModal.data.totalPages = resp.data.totalPages;
	            // 调用分页
	            laypage({
	                cont : 'page_bar',
	                pages : $scope.scheduleModal.data.totalPages,// 得到总页数
	                skin : '#12bdce',
	                skip : true, // 是否开启跳页
	                prev : '<', // 若不显示，设置false即可
	                next : '>', // 若不显示，设置false即可
	                groups : 5, //连续分页数
	                curr: 1, //初始化当前页
	                jump : function(obj,first) {// 触发分页后的回调
	                    /*obj是一个object类型。包括了分页的所有配置信息。
	                     first一个Boolean类，检测页面是否初始加载。非常有用，可避免无限刷新。*/
	                    if(!first){
	                        $scope.scheduleModal.param.month = $scope.scheduleModal.data.month;
	                        $scope.scheduleModal.param.pageIndex = obj.curr - 1;
	                        Page.ajaxPost('schedule/queryBillSources.do', $scope.scheduleModal.param, function(
	                            resp) {
	                            $scope.scheduleModal.data.months = resp.data.months;
					            $scope.scheduleModal.data.days = resp.data.daysArray;
					            $scope.scheduleModal.data.dataArray = resp.data.dataArray;
					            
					            $scope.scheduleModal.data.month = resp.data.currentMonth;
					            $scope.scheduleModal.data.lastYear = resp.data.lastYear;
					            $scope.scheduleModal.data.nextYear = resp.data.nextYear;
					            $scope.scheduleModal.data.totalPages = resp.data.totalPages;
	                        });
	                    }
	                }
	            })
	        });
    	},
    	checkSource : function($event,data){
    		if($event.target.checked) {
	            this.checkResources.put(data.resourceId,data);
	        } else {
	            this.checkResources.remove(data.resourceId);
	        }
    	},
        onOkClick : function() {
            this.hide();
			if(angular.isFunction(this.callBack)){
				this.callBack(this.checkResources);
			}
        },
        onHidden : function() {
            
        }
    }
    
    $scope.makeBillViewModal  = {
    	open : function(billId){
    		this.billId = billId;
    		this.show();
    	},
    	onShow : function(){
    		Page.ajaxPost('publishBill/' + this.billId + '/info.do', null, function(resp) {
    			$scope.makeBillViewModal.publishBill = resp.data;
    			$scope.makeBillViewModal.setTitle("上刊详情-" + resp.data.billNo);
    			Page.ajaxPostQuiet('customer/' +  resp.data.customerId + '/info.do', null, function (resp) {
			      	$scope.makeBillViewModal.customer = resp.data;
			 	});
    		});
    		
    		Page.ajaxPostQuiet('publishBill/queryBillDetails.do', {billId : this.billId}, function (resp) {
                $scope.makeBillViewModal.billDetails = resp.data.array;
				var bidFiles = resp.data.fileArray;
				var bidImgs = resp.data.imgArray;
				$scope.makeBillViewModal.publishFile = bidFiles.length > 0 ? bidFiles[0]:null;
				$scope.makeBillViewModal.adModelImgs = bidImgs;
            });
    		
    		Page.ajaxPost('publishBill/' + this.billId + '/makeBills.do', null, function(resp) {
    			$scope.makeBillViewModal.makeBills = resp.data;
    		});
    	}
    }
}]);
